package itsm.isperp.framework.web.controller;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.data.domain.QueryFilter;
import itsm.isperp.framework.service.TreeNodeService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 树形结构控制器，继承于{@link BaseController}
 * 
 * @author lizx
 * @date 2013-3-2
 * @version V1.0
 */
@Component
public abstract class TreeNodeController<T extends ITreeNode> extends
		BaseController<T> {

	/**
	 * 获取属性节点服务
	 */
	@Override
	public abstract TreeNodeService<T> getService();

	@RequestMapping("list")
	@ResponseBody
	@Override
	public PageResponse<T> list(JqGridRequest request, HttpServletRequest req) {
		request.setSort("order_num", Direction.ASC);
		return this.getService().findAll(request).toPage();

	}

	/**
	 * 编辑树形结构数据，参数中parentId是节点的父节点唯一标识
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 */
	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) {
		String parentId = req.getParameter("parentId");
		ModelAndView mv = new ModelAndView();
		T model;
		ITreeNode parent = null;
		if (StringUtils.isEmpty(id)) {

			Type genType = getClass().getGenericSuperclass();
			Type[] params = ((ParameterizedType) genType)
					.getActualTypeArguments();
			try {
				model = ((Class<T>) params[0]).newInstance();
				model.setId(HibernateUUIDGenerator.generate());
				QueryFilter filter = new JqGridFilter();
				filter.addRule("parentId", JqGridFilterRuleOp.eq, parentId);
				int count = this.getService().findAllCount(filter).intValue();
				model.setOrderNum(count + 1);

			} catch (Exception e) {
				throw new RuntimeException("实例化实体失败", e);
			}

			// 新建界面则需要设定父级菜单的值
			if (StringUtils.isEmpty(parentId)) {

				parent = TreeNodeUtils
						.creatRootTreenode(((Class<T>) params[0]));
				parentId = "";
			} else {
				parent = this.getService().findOne(parentId);
			}

			model.setParentId(parentId);
		} else {
			model = this.getService().findOne(id);
			parent = this.getService().findOne(model.getParentId());
			if (parent == null) {
				Type genType = getClass().getGenericSuperclass();
				Type[] params = ((ParameterizedType) genType)
						.getActualTypeArguments();
				parent = TreeNodeUtils.creatRootTreenode((Class<T>) params[0]);
			}
		}
		mv.addObject("model", model);
		mv.addObject("parentName", parent == null ? null : parent.getName());
		// 控制器返回到编辑的界面
		mv.setViewName(this.getModulePath() + "/edit");
		return mv;

	}

	/**
	 * 取得树形结构的的json数据
	 * 
	 * @return 菜单的json数据
	 */
	@RequestMapping("getTree")
	@ResponseBody
	public List<T> getTree(String id, boolean asyncLoad, String parentId,
			boolean showRoot, HttpServletRequest req) {
		if (asyncLoad) {

			return this.getService().getChildren(id, showRoot);
		}

		return this.getService().getTree(parentId, showRoot);
	}

	@RequestMapping("getTreeDetail")
	@ResponseBody
	public List<T> getTreeDetail(String parentId, String allColumns) {
		return this.getService().getTree(parentId, "*");
	}

}
